<template>
    <div ref="appContainer" class="app-container slideform-mode">
        <div class="tool-container">
            <el-button class="tool-btn tool-btn-sub" type="primary" :disabled="disableDels" @click="$clickAuth('Del')&&handleDeletes()">{{ $t('global.del') }}</el-button>
            <el-button class="tool-btn" type="primary" :disabled="!disableDels" @click="$clickAuth('Insert') && handleCreate()">{{ $t('global.insert') }}</el-button>
        </div>
        <div class="table-container">
            <div class="table-area">
                <el-table
                    :key="tableKey"
                    v-loading="listLoading"
                    height="calc(100vh - 250px)"
                    :data="list"
                    border
                    highlight-current-row
                    @selection-change="tableSelect"
                    @row-click="$clickAuth('Update')&&handleRowClick($event)"
                >
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column :label="$t('admin.status')" prop="status" align="center" width="80">
                        <template slot-scope="{row}">
                            <div @click.stop="">
                                <el-switch :value="row.adminStatus" :active-value="200" :inactive-value="100" :disabled="$authCheck('Update')" @change="handleSwitch($event, row)" />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('admin.name')" min-width="80px" align="center" prop="adminName" />
                    <el-table-column :label="$t('admin.belongName')" min-width="70px" align="center">
                        <template slot-scope="{row}">
                            <span>{{ row.role && row.role.roleName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('admin.creativeTime')" width="110px" align="center">
                        <template slot-scope="{row}">
                            <span>{{ parseTime(row.createdTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('admin.resetPwd')" align="center" width="160" class-name="small-padding fixed-width">
                        <template slot-scope="{row}">
                            <el-button type="primary" size="mini" @click.stop="$clickAuth('Update')&&handleRePwd(row)">{{ $t('admin.resetPwdBtn') }}</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
            </div>
            <div class="editform-area" :class="{'slide-form-show':slideFormVisible}">
                <div class="editform-bg">
                    <div class="editform-bg-tit">{{ $t('admin.admin') }}</div>
                    <img class="editform-bg-img" src="@/assets/imgs/bg/userAdmin.png" alt="">
                    <el-button class="editform-btn" type="primary" :disabled="!disableDels" @click="$clickAuth('Insert')&&handleCreate()">{{ $t('global.insert') }}</el-button>
                </div>
                <transition name="fade-transform" mode="out-in">
                    <div v-show="slideFormVisible" class="slide-form-area">
                        <el-form ref="slideForm" class="slideForm-form" :rules="slideFormRules" :model="temp" label-position="top">
                            <el-form-item :label="$t('admin.account')" prop="adminPhone">
                                <el-input v-model.number="temp.adminPhone" type="tel" />
                            </el-form-item>
                            <el-form-item :label="$t('admin.adminName')" prop="adminName">
                                <el-input v-model="temp.adminName" type="text" />
                            </el-form-item>
                            <el-form-item :label="$t('admin.belongName')" prop="adminRoleId">
                                <el-select v-model="temp.adminRoleId" clearable>
                                    <el-option v-for="item in roles" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
                                </el-select>
                            </el-form-item>
                            <el-form-item v-show="!temp.adminId" :label="$t('admin.pwd')" prop="adminPassword">
                                <el-input v-model="temp.adminPassword" type="password" :placeholder="$t('admin.defaultPwd')" autocomplete="off" />
                            </el-form-item>
                        </el-form>
                        <div class="slide-form-btn-box">
                            <el-button v-loading="submitLoading" class="slide-form-btn" type="primary" @click="slideFormSubmit">{{ $t('global.save') }}</el-button>
                        </div>
                    </div>
                </transition>
            </div>
            <el-dialog :title="$t('admin.resetPwd')" custom-class="custom-dialog-form" :visible.sync="dialogRepwdVisible" width="420px" :close-on-click-modal="false">
                <el-form ref="rePwdForm" :rules="dialogRepwdRules" :model="rePwd" label-position="top">
                    <el-form-item :label="$t('admin.resetPwd')" prop="newPwd">
                        <el-input v-model="rePwd.newPwd" type="password" :placeholder="$t('admin.resetPwdTips')" />
                    </el-form-item>
                    <el-form-item :label="$t('admin.confirmPwd')" prop="checkPwd">
                        <el-input v-model="rePwd.checkPwd" type="password" :placeholder="$t('admin.confirmPwd')" />
                    </el-form-item>
                    <div class="el-message-box__btns">
                        <button type="button" class="el-button" @click="dialogRepwdVisible = false">{{ $t('global.cancel') }}</button>
                        <button v-loading="submitLoading" type="button" class="el-button" @click="handleResetPwdBtn">{{ $t('global.save') }}</button>
                    </div>
                </el-form>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { adminSearch, adminInsert, adminDeletes, adminUpdate, adminRePwd } from '@/api/admin/admin'
import { roleSearch } from '@/api/admin/adminRole'
import { parseTime } from '@/utils'
import { regPwd, validateReg } from '@/utils/validate-reg'
import Pagination from '@/components/Pagination'; // secondary package based on el-pagination
import { isEmpty } from 'lodash'

export default {
    name: 'TableSlideForm',
    components: { Pagination },
    data() {
        return {
            disableDels: true,
            dialogRepwdVisible: false,
            tableKey: 0,
            list: null,
            total: 0,
            submitLoading: false,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 10
            },
            temp: {
                adminId: null,
                adminPhone: '',
                adminName: '',
                adminRoleId: '',
                adminPassword: null
            },
            selectItems: [],
            slideFormVisible: false,
            roles: [],
            rePwd: {
                adminId: null,
                newPwd: null,
                checkPwd: null
            }
        };
    },
    computed: {
        slideFormRules() {
            return {
                adminPhone: [{ required: true, message: this.$t('tips.input'), trigger: 'blur' }],
                adminName: [{ required: true, message: this.$t('admin.nameTips'), trigger: 'blur' }],
                adminRoleId: [{ required: true, message: this.$t('admin.roleTips'), trigger: 'blur' }],
                adminPassword: [{
                    validator: (rule, value, callback) => {
                        if (isEmpty(value) || value.length < 6) {
                            callback(new Error(this.$t('admin.pwdLength')));
                        } else if (!regPwd(value)) {
                            callback(new Error(this.$t('admin.pwdReq')));
                        } else {
                            callback();
                        }
                    },
                    trigger: 'blur'
                }]
            }
        },
        dialogRepwdRules() {
            return {
                newPwd: [{
                    validator: (rule, value, callback) => {
                        if (isEmpty(value) || value.length < 6) {
                            callback(new Error(this.$t('admin.pwdLength')));
                        } else if (!regPwd(value)) {
                            callback(new Error(this.$t('admin.pwdReq')));
                        } else {
                            callback();
                        }
                    },
                    trigger: 'blur' }],
                checkPwd: [{
                    required: true, trigger: 'blur', validator: (rule, value, callback) => {
                        if (value === null) {
                            callback(new Error(this.$t('admin.pwdReTips')));
                        } else if (value !== this.rePwd.newPwd) {
                            callback(new Error(this.$t('admin.pwdNoSame')));
                        } else {
                            callback();
                        }
                    }
                }]
            }
        }
    },
    created() {
        roleSearch({}).then(res => {
            this.roles = res.data;
            this.getList();
        });
    },
    methods: {
        parseTime,
        getList() {
            this.listLoading = true;
            adminSearch(this.listQuery).then(response => {
                this.list = response.data;
                this.total = response.count;
                this.listLoading = false;
            });
        },
        resetTemp() {
            this.temp = {
                adminId: null,
                adminPhone: '',
                adminName: '',
                adminRoleId: '',
                adminPassword: null
            };
        },
        // 切换开关
        handleSwitch(val, row) {
            console.log(val, row.adminId);
            var lastStatus = row.adminStatus;
            row.adminStatus = val;
            const param = { adminId: row.adminId, adminStatus: val };
            adminUpdate(param).catch(res => {
                row.adminStatus = lastStatus;
                this.$notify({
                    type: 'error',
                    title: this.$t('global.fail'),
                    message: this.$t('global.fail')
                });
            });
        },
        // 多选
        tableSelect(selection) {
            this.slideFormVisible = false;
            this.disableDels = selection.length <= 0;
            this.selectItems = selection.map((i) => {
                return i.adminId;
            });
            console.log(selection);
        },
        // 多选删除
        handleDeletes() {
            console.log(this.selectItems);
            this.$confirm(this.$t('extra.confirmDelete'), this.$t('global.hint'), {
                customClass: 'custom-msgbox',
                center: true
            }).then(() => {
                adminDeletes(this.selectItems).then(res => {
                    this.getList(); // 刷新列表
                    this.$notify({
                        type: 'success',
                        message: this.$t('tips.successDel')
                    });
                });
            });
        },
        // 打开修改密码
        handleRePwd(row) {
            this.dialogRepwdVisible = true;
            this.rePwd = {
                adminId: row.adminId,
                newPwd: null,
                checkPwd: null
            };
            this.$nextTick(() => {
                this.$refs['rePwdForm'].clearValidate();
            });
        },
        // 重置密码提交
        handleResetPwdBtn() {
            this.$refs['rePwdForm'].validate((valid, item) => {
                if (valid) {
                    const param = { adminId: this.rePwd.adminId, adminPassword: this.rePwd.newPwd };
                    console.log(param);
                    this.submitLoading = true
                    adminRePwd(param).then(res => {
                        this.dialogRepwdVisible = false;
                        this.$notify({
                            title: this.$t('global.success'),
                            message: this.$t('admin.resetPwdSuccess'),
                            type: 'success'
                        });
                    }).finally(res => {
                        this.submitLoading = false
                    })
                }
            });
        },
        // 行内点击
        handleRowClick(row, column, event) {
            if (!this.$clickAuth('Update')) {
                return false;
            }
            for (const key in this.temp) {
                if (key === 'adminPassword') continue;
                this.temp[key] = row[key];
            }
            this.slideFormVisible = true;
            this.$nextTick(() => {
                this.$refs['slideForm'].clearValidate();
            });
        },
        // 新增点击
        handleCreate() {
            this.resetTemp();
            this.slideFormVisible = true;
            this.$nextTick(() => {
                this.$refs['slideForm'].clearValidate();
            });
        },
        // 新增|修改提交
        slideFormSubmit() {
            this.$refs['slideForm'].validate((valid, item) => {
                if (valid) {
                    console.log(this.temp);
                    this.submitLoading = true
                    if (this.temp.adminId) {
                        // 修改
                        adminUpdate(this.temp).then(res => {
                            this.getList(); // 刷新列表
                            this.slideFormVisible = false; // 关闭侧表单
                            this.$notify({
                                title: this.$t('global.success'),
                                message: this.$t('global.editSuccess'),
                                type: 'success'
                            });
                        }).finally(res => {
                            this.submitLoading = false
                        });
                    } else {
                        adminInsert(this.temp).then(res => {
                            this.getList(); // 刷新列表
                            this.slideFormVisible = false; // 关闭侧表单
                            this.$notify({
                                message: this.$t('admin.insertSuccess'),
                                type: 'success'
                            });
                        }).finally(res => {
                            this.submitLoading = false
                        });
                    }
                }
            });
        }
    }
};
</script>
